#!/bin/bash

function usage
{
  echo "Usage:"
  echo "  -t timestamp exe"
  echo "  -o Path to file to create"
  echo "  -s Size of file to create"
  echo "  -l Test label"
  echo "  -e Experiment name"
}

while getopts "t:o:s:b:u:p:l:e:" o; do
  case $o in
	t)
	  TIMESTAMPEXE="$OPTARG"
	  ;;
	o)
	  TESTFILEPATH="$OPTARG"
	  ;;
	s)
	  TESTFILESIZE=$OPTARG
	  ;;
	l)
	  TESTLABEL="$OPTARG"
	  ;;
	e)
	  EXPERIMENTNAME="$OPTARG"
	  ;;
        ? | *)
	  echo "Incorrect options passed to fileupload"
	  usage
	  exit 1
  esac
done

if [ $OPTIND -le $# ]; then
  echo "Too many options passed to fileupload"
  usage
  exit 1
fi

# Option checking
[ -z "${TIMESTAMPEXE+set}" ] || [ ! -f $TIMESTAMPEXE ] && exit 1
[ -z "${TESTFILEPATH+set}" ] || [ -e $TESTFILEPATH ] && exit 1
[ -z "${TESTFILESIZE+set}" ] && exit 1
[ -z "${TESTLABEL+set}" ] && exit 1
[ -z "${EXPERIMENTNAME+set}" ] && exit 1

# Calculate the name of the file
TESTFILENAME=$(basename "$TESTFILEPATH")

# If start date and time is not recorded, look them up to print in results (we also use timestamps to record how long each stage takes)
[ -z "${TESTSTARTDATE+set}" ] && TESTSTARTDATE=$(date +"%Y%m%d")
[ -z "${TESTSTARTTIME+set}" ] && TESTSTARTTIME=$(date +"%H%M%S")

# Generate data, write it to HDC and standard out and generate a hash from standard out
DDSTARTTIME=$($TIMESTAMPEXE)
DDHASH=$(dd if=/dev/urandom bs=1m count=$TESTFILESIZE 2>/dev/null | tee $TESTFILEPATH | /usr/bin/openssl sha1)
DDENDTIME=$($TIMESTAMPEXE)

# Generate hash for the file stored in HDC's file system (after HDC hashing is complete)
FSSTARTTIME=$($TIMESTAMPEXE)
FSHASH=$(/usr/bin/openssl sha1 $TESTFILEPATH | awk '{ print $2 }')
FSENDTIME=$($TIMESTAMPEXE)

# Calculate times
DDTIMETAKEN=$(bc -l <<< "scale=3;($DDENDTIME-$DDSTARTTIME)/1000000.0")
FSTIMETAKEN=$(bc -l <<< "scale=3;($FSENDTIME-$FSSTARTTIME)/1000000.0")

# Check the file size in HDC is correct
FSFILESIZE=$(stat -f "%z" $TESTFILEPATH)

# Uncomment the following lines to test if matching works (introduces a chance that the HASH will not match)
#[ "$RANDOM" -le 7500 ] && FSHASH=BROKEN

if [ "$DDHASH" = "$FSHASH" ]; then
  FSHASHMATCH=Match
else
  FSHASHMATCH=Mismatch
fi

# Print results to standard out
printf "%s,%s,,%s,%s,%.0f,,%.0f,%.0f,,%s,,,%s,%s,%s\n" $DDHASH $FSHASH $EXPERIMENTNAME $TESTFILENAME $FSFILESIZE $DDTIMETAKEN $FSTIMETAKEN $FSHASHMATCH $TESTLABEL $TESTSTARTDATE $TESTSTARTTIME
